package cn.edu.sjtu.se.dslab.rhapsody.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import cn.edu.sjtu.se.dslab.util.FileUtil;

public abstract class RhapsodyFileGenerator {
	private static final Logger logger = Logger.getLogger(RhapsodyFileGenerator.class);
	
	public static final String TEMPLATE_PATH = "systemdata/velocity_template/rhapsody";

	private VelocityEngine ve = null;
	private VelocityContext vc = null;
	private Template template = null;

	public abstract String generateFile(long projectId) throws IOException;

	public RhapsodyFileGenerator() {
		ve = new VelocityEngine();
		String templateDir = FileUtil.getRootPath() + TEMPLATE_PATH;
		Properties properties = new Properties();
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,
				templateDir);
		ve.init(properties);
		vc = new VelocityContext();
	}

	protected void inputData(String key, Object value) {
		vc.put(key, value);
	}

	protected void generateCodeFile(String targetFilePath, String templateFile) {
		logger.info("generate rhapsody file: " + targetFilePath);
		FileWriter fWriter = null;
		try {
			File writeFile = FileUtil.getOldOrCreateFile(targetFilePath);
			fWriter = new FileWriter(writeFile);
			if (loadTemplage(templateFile)) {
				template.merge(vc, fWriter);
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fWriter.flush();
				fWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private boolean loadTemplage(String templateFile) {
		template = ve.getTemplate(templateFile);
		if (template != null)
			return true;
		return false;
	}
}
